package com.yangyang.dingnote;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.Canvas;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.appbar.MaterialToolbar;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;
import java.util.List;

import it.xabaras.android.recyclerview.swipedecorator.RecyclerViewSwipeDecorator;

public class MainFragment extends Fragment {
    private NoteDatabaseHelper databaseHelper;
    private RecyclerView notesRecyclerView;
    private NoteAdapter noteAdapter;
    private List<Note> notes = new ArrayList<>();
    private SharedViewModel viewModel;
    //private ExtendedFloatingActionButton fab;
    private FloatingActionButton fab;
    private ClipboardManager clipboardManager;

    //创建并返回 Fragment 的视图层级
    //在 onCreate() 之后
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // 初始化数据库
        databaseHelper = new NoteDatabaseHelper(getContext());

        View view = inflater.inflate(R.layout.fragment_main, container, false);
        clipboardManager = (ClipboardManager) requireActivity().getSystemService(Context.CLIPBOARD_SERVICE);

        // 初始化 RecyclerView
        notesRecyclerView = view.findViewById(R.id.notesRecyclerView);
        notesRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        // 初始化 Adapter
        noteAdapter = new NoteAdapter(notes, new NoteAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(Note note) {
                // 点击便签，跳转到编辑页面
                Bundle bundle = new Bundle();
                bundle.putParcelable("note", note);
                Navigation.findNavController(view).navigate(R.id.action_mainFragment_to_editNoteFragment, bundle);
            }

            @Override
            public void onItemLongClick(Note note) {
                // 长按删除
                new AlertDialog.Builder(requireContext())
                        .setTitle("删除笔记")
                        .setMessage("确定要删除这条笔记吗？")
                        .setPositiveButton("删除", (dialog, which) -> {
                            databaseHelper.deleteNote(note.getId());
                            loadNotesFromDatabase();
                        })
                        .setNegativeButton("取消", null)
                        .show();
            }
        });
        notesRecyclerView.setAdapter(noteAdapter);

        // 加载便签数据
        //loadNotes();

        // 修改加载笔记方法
        loadNotesFromDatabase();


        // 绑定按钮点击事件
        MaterialButton btnAdd = view.findViewById(R.id.btn_add);
        MaterialButton btnPaste = view.findViewById(R.id.btn_paste);
        MaterialButton btnSettings = view.findViewById(R.id.btn_settings);

        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 新增功能 - 与FAB相同
                Navigation.findNavController(view).navigate(R.id.action_mainFragment_to_editNoteFragment);
            }
        });

        btnPaste.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 粘贴功能 - 检查剪贴板是否有内容
                if (clipboardManager.hasPrimaryClip()) {
                    ClipData.Item item = clipboardManager.getPrimaryClip().getItemAt(0);
                    String clipboardText = item.getText().toString();

                    // 创建新笔记并传递剪贴板内容，明确设置ID为-1表示新笔记
                    Note newNote = new Note("", clipboardText);
                    newNote.setId(-1);  // 明确标识这是一个新笔记
                    Bundle bundle = new Bundle();
                    bundle.putParcelable("note", newNote);
                    //bundle.putBoolean("isNewNote", true); // 显式标记为新笔记
                    Navigation.findNavController(view).navigate(R.id.action_mainFragment_to_editNoteFragment, bundle);
                } else {
                    Toast.makeText(getActivity(), "剪贴板为空", Toast.LENGTH_SHORT).show();
                }
            }
        });

        btnSettings.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 设置功能 - 暂时只显示Toast
                Toast.makeText(getActivity(), "设置功能待实现", Toast.LENGTH_SHORT).show();

                //TODO 1 测试刷新列表
                loadNotesFromDatabase();
            }
        });


        return view;
    }

//    private void loadNotes() {
//        // 从数据库或网络加载便签数据
//        notes.clear();
//        notes.addAll(getSampleNotes()); // 示例数据
//        noteAdapter.notifyDataSetChanged();
//    }

    private void loadNotesFromDatabase() {
        notes.clear();
        notes.addAll(databaseHelper.getAllNotes());
        noteAdapter.notifyDataSetChanged();
    }


//    private List<Note> getSampleNotes() {
//        List<Note> sampleNotes = new ArrayList<>();
//        sampleNotes.add(new Note("标题1", "内容1"));
//        sampleNotes.add(new Note("标题2", "内容2"));
//
//        for (int i = 3; i <= 20; i++) {
//            sampleNotes.add(new Note("标题" + i, "内容" + i));
//        }
//
//        return sampleNotes;
//    }

    //在视图创建完成后初始化控件和逻辑
    //在 onCreateView() 之后
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        MaterialToolbar toolbar = view.findViewById(R.id.toolbar);
        toolbar.setNavigationOnClickListener(v -> {
            Navigation.findNavController(view).navigateUp();
        });

        // 初始化ViewModel（与Activity共享）
        viewModel = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);

        // 绑定FAB
        fab = view.findViewById(R.id.fab);
        fab.setOnClickListener(v -> {
            // 点击事件处理
            Navigation.findNavController(v).navigate(R.id.action_mainFragment_to_editNoteFragment);
        });

        // 观察Visibility变化
        viewModel.getFabVisibility().observe(getViewLifecycleOwner(), visible -> {
            fab.setVisibility(visible ? View.VISIBLE : View.GONE);
        });


        // 在 MainFragment 的 onViewCreated 方法中添加：
        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(
                0, // 拖拽方向（0表示禁用拖拽）
                ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT // 允许左右滑动
        ) {
            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
                return false; // 禁用拖拽排序
            }

            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
                int position = viewHolder.getAdapterPosition();
                if (position == RecyclerView.NO_POSITION) return; // 防止无效 position

//                if (direction == ItemTouchHelper.LEFT) {
//                    // 左滑删除
//                    noteAdapter.deleteNote(position);
//                    databaseHelper.deleteNote(noteAdapter.getNoteId(position)); // 从数据库删除
//                } else if (direction == ItemTouchHelper.RIGHT) {
//                    // 右滑归档
//                    noteAdapter.archiveNote(position);
//                    databaseHelper.archiveNote(noteAdapter.getNoteId(position)); // 假设数据库有归档方法
//                }

                // 先获取数据，再删除
                long noteId = noteAdapter.getNoteId(position); // 先获取 ID
                //Note note = noteAdapter.getNote(position);     // 先获取 Note 对象

                if (direction == ItemTouchHelper.LEFT) {
                    // 左滑删除
                    databaseHelper.deleteNote(noteId); // 先删除数据库
                    noteAdapter.deleteNote(position);  // 再删除列表数据
                } else if (direction == ItemTouchHelper.RIGHT) {
                    // 右滑归档
                    databaseHelper.archiveNote(noteId); // 先更新数据库
                    noteAdapter.archiveNote(position);  // 再更新列表数据
                }
            }

            // 可选：设置滑动时的背景色和图标
            @Override
            public void onChildDraw(@NonNull Canvas c, @NonNull RecyclerView recyclerView,
                                    @NonNull RecyclerView.ViewHolder viewHolder,
                                    float dX, float dY, int actionState, boolean isCurrentlyActive) {
                // 自定义滑动时的UI效果（例如显示红色背景+删除图标）
                new RecyclerViewSwipeDecorator.Builder(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
                        .addSwipeLeftBackgroundColor(ContextCompat.getColor(requireContext(), R.color.delete_red))
                        .addSwipeLeftActionIcon(R.drawable.baseline_delete_24)
                        .addSwipeRightBackgroundColor(ContextCompat.getColor(requireContext(), R.color.archive_green))
                        .addSwipeRightActionIcon(R.drawable.baseline_archive_24)
                        .create()
                        .decorate();
                super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
            }
        });

        // 绑定到 RecyclerView
        itemTouchHelper.attachToRecyclerView(notesRecyclerView);
    }
}
